package com.bw.z.mvp.view.live;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bw.z.R;
import com.bw.z.db.DBManager;
import com.bw.z.db.UserTable;
import com.bw.z.mvp.HttpCode;
import com.bw.z.mvp.base.view.BaseActivity;
import com.bw.z.mvp.contract.NewsContract;
import com.bw.z.mvp.di.DaggerNewsComponent;
import com.bw.z.mvp.di.NewsModules;
import com.bw.z.mvp.model.entity.BaseEntity;
import com.bw.z.mvp.model.entity.LiveCommentEntity;
import com.bw.z.mvp.presenter.NewsPresenter;
import com.bw.z.mvp.view.live.adapter.LiveCommentAdapter;
import com.bw.z.mvp.view.live.adapter.LiveVpAdapter;
import com.bw.z.mvp.view.news.NewsValuesActivity;
import com.bw.z.utils.GlideUtils;
import com.bw.z.utils.LogUtils;
import com.bw.z.utils.SpUtils;
import com.bw.z.utils.ToastUtils;
import com.google.android.material.appbar.AppBarLayout;
import com.tb.emoji.Emoji;
import com.tb.emoji.EmojiUtil;
import com.tb.emoji.FaceFragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LiveValuesActivity extends BaseActivity<NewsPresenter>
        implements NewsContract.NewView, View.OnClickListener,
        FaceFragment.OnEmojiClickListener {

    private long live_id;
    private String live_url;
    private com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer liveGsyPlayer;
    private com.flyco.tablayout.SlidingTabLayout liveValuesTab;
    private androidx.viewpager.widget.ViewPager liveValuesVp;
    private LiveVpAdapter vpAdapter;
    private LiveCommentAdapter adapter;
    private android.widget.RelativeLayout liveValuesEdtBtn;
    private android.widget.ImageView liveValuesFaceImg;
    private ImageView liveCollectionImg;
    private RelativeLayout liveMsgRelative;
    private RelativeLayout liveBottomView;
    private android.widget.EditText liveMsgEdt;
    private android.widget.TextView liveSendTv;
    private ImageView liveVoiceImg;
    private ImageView liveEmojiImg;
    private android.widget.LinearLayout liveEmojiLinear;
    //当前界面中appbarLayout展开以及折叠标志,false折叠true展开
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private List<LiveCommentEntity.Values> list = new ArrayList<>();

    @Override
    public View addStatusView() {
        return f(R.id.live_values_root);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_live_values;
    }

    @Override
    public void initView() {
        getColors(Color.WHITE);
        live_id = getIntent().getExtras().getLong("live_id");
        live_url = getIntent().getExtras().getString("live_url");
        LogUtils.show("live_url:" + live_url);
        liveGsyPlayer = findViewById(R.id.live_gsy_player);
        liveValuesTab = findViewById(R.id.live_values_tab);
        liveValuesVp = findViewById(R.id.live_values_vp);
        liveValuesEdtBtn = findViewById(R.id.live_values_edt_btn);
        liveValuesFaceImg = findViewById(R.id.live_values_face_img);
        liveCollectionImg = findViewById(R.id.live_collection_img);
        liveMsgRelative = findViewById(R.id.live_msg_relative);
        liveBottomView = findViewById(R.id.live_bottom_view);
        liveMsgEdt = findViewById(R.id.live_msg_edt);
        liveSendTv = findViewById(R.id.live_send_tv);
        liveVoiceImg = findViewById(R.id.live_voice_img);
        liveEmojiImg = findViewById(R.id.live_emoji_img);
        liveEmojiLinear = findViewById(R.id.live_emoji_linear);
        liveValuesEdtBtn.setOnClickListener(this::onClick);
        liveValuesFaceImg.setOnClickListener(this::onClick);
        liveEmojiImg.setOnClickListener(this::onClick);
        liveSendTv.setOnClickListener(this::onClick);
        liveMsgRelative.setOnClickListener(this::onClick);
        liveCollectionImg.setOnClickListener(this::onClick);

        vpAdapter = new LiveVpAdapter();
        liveValuesVp.setAdapter(vpAdapter);
        liveValuesTab.setViewPager(liveValuesVp);
        adapter = new LiveCommentAdapter();
        liveGsyPlayer.setUp(live_url, true, "");
        liveGsyPlayer.startPlayLogic();
        initListener();

        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true
        option.setNeedNewVersionRgc(true);
        option.setAddrType("all");
        //可选，设置是否需要最新版本的地址信息。默认需要，即参数为true
        mLocationClient.setLocOption(option);
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            String city = location.getCity();    //获取城市
            UserTable load = new DBManager(LiveValuesActivity.this).getDaoSession().getUserTableDao().load(SpUtils.readDataLong("user_id"));
            Map<String, Object> map = new HashMap<>();
            map.put("code", HttpCode.LIVEADDCOMMENTCODE);
            map.put("comment_address", city + "");
            map.put("comment_time", System.currentTimeMillis() / 1000);
            map.put("comment_value", liveMsgEdt.getText().toString());
            map.put("lc_id", 1);
            map.put("live_id", live_id);
            map.put("user_id", load.getUser_id());
            //发布评论
            p.requestAll(map);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.live_values_edt_btn:
                liveBottomView.setVisibility(View.VISIBLE);
                liveEmojiLinear.setVisibility(View.GONE);
                break;
            case R.id.live_values_face_img:
                if (liveEmojiLinear.getVisibility() == View.VISIBLE) {
                    //当前正在显示表情系统->隐藏掉表情布局
                    liveEmojiLinear.setVisibility(View.GONE);
                    liveEmojiImg.setImageResource(R.mipmap.res_7icon_129);
                } else {
                    //当前正在隐藏表情系统->显示表情布局
                    liveEmojiLinear.setVisibility(View.VISIBLE);
                    liveEmojiImg.setImageResource(R.mipmap.res_7icon_131);
                }
                break;
            case R.id.live_send_tv:
                if (liveMsgEdt.getText() == null) {
                    ToastUtils.showMsg("请输入评论内容");
                    return;
                }
                if (liveMsgEdt.getText().toString().isEmpty()) {
                    ToastUtils.showMsg("请输入评论内容");
                    return;
                }
                //开启定位
                mLocationClient.start();
                break;
            case R.id.live_face_img:
                liveBottomView.setVisibility(View.VISIBLE);
                liveEmojiLinear.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void initListener() {
//        liveGsyPlayer.getRootView()
        liveGsyPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        liveGsyPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("live_url", live_url);
                startPage(bundle, FullVideoActivity.class);
            }
        });
    }

    @Override
    public void inject() {
        DaggerNewsComponent.builder().newsModules(new NewsModules(this)).build().injectLiveValuesNews(this);
    }

    @Override
    public void initData() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpCode.SELLIVECOMMENTCODE);
        LogUtils.show("live_id:" + live_id);
        map.put("live_id", 1);
        p.requestAll(map);
    }

    @Override
    protected void onResume() {
        super.onResume();
        liveGsyPlayer.getCurrentPlayer().onVideoResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        liveGsyPlayer.getCurrentPlayer().onVideoPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        liveGsyPlayer.getCurrentPlayer().release();
    }

    @Override
    public void refreshAll(BaseEntity baseEntity) {
        if (baseEntity instanceof LiveCommentEntity) {
            LiveCommentEntity entity = (LiveCommentEntity) baseEntity;
            vpAdapter.getRootRv().setAdapter(adapter);
            if (entity.getValues() == null)
                return;
            list = adapter.getData();
            list.addAll(entity.getValues());
            LogUtils.show("LiveValuesActivity:" + entity.getValues().size());
            adapter.setNewInstance(list);
            adapter.notifyDataSetChanged();
        } else {
            if (baseEntity.message.equals("发表成功")) {
                ToastUtils.showMsg("发表成功");
                //当前评论发布成功
                //清空输入框
                liveMsgEdt.setText("");
                //隐藏输入框
                liveBottomView.setVisibility(View.GONE);
                //刷新评论列表数据
                //请求获取最新评论列表
                initData();
            }
        }
    }

    @Override
    public void refreshRecyclerView(BaseEntity baseEntity) {

    }

    @Override
    public void loadMoreRecyclerView(BaseEntity baseEntity) {

    }

    @Override
    public void onEmojiDelete() {
        String text = liveMsgEdt.getText().toString();
        if (text.isEmpty()) {
            return;
        }
        if ("]".equals(text.substring(text.length() - 1, text.length()))) {
            int index = text.lastIndexOf("[");
            if (index == -1) {
                int action = KeyEvent.ACTION_DOWN;
                int code = KeyEvent.KEYCODE_DEL;
                KeyEvent event = new KeyEvent(action, code);
                liveMsgEdt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
                try {
                    EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            liveMsgEdt.getText().delete(index, text.length());
            try {
                EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        int action = KeyEvent.ACTION_DOWN;
        int code = KeyEvent.KEYCODE_DEL;
        KeyEvent event = new KeyEvent(action, code);
        liveMsgEdt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
        try {
            EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (liveBottomView.getVisibility() == View.VISIBLE) {
                liveBottomView.setVisibility(View.GONE);
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onEmojiClick(Emoji emoji) {
        if (emoji != null) {
            int index = liveMsgEdt.getSelectionStart();
            Editable editable = liveMsgEdt.getEditableText();
            if (index < 0) {
                editable.append(emoji.getContent());
            } else {
                editable.insert(index, emoji.getContent());
            }
            try {
                EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}